package collection;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.HashMap;

public class QueryParamsExtractor {

    public static void main(String[] args) {
        String path = "http://localhost:8088/myweb/reg?name=zhangsan&pwd=123456&nick=san&age=16";

        try {
            Map<String, String> params = extractQueryParams(path);

            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println("参数名:" + entry.getKey() + " 参数值:" + entry.getValue());
            }
        } catch (UnsupportedEncodingException | MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从URL中提取查询参数
     *
     * @param urlStr URL字符串
     * @return 查询参数的Map
     * @throws UnsupportedEncodingException 如果解码失败
     */
    public static Map<String, String> extractQueryParams(String urlStr) throws UnsupportedEncodingException, MalformedURLException {
        Map<String, String> query_pairs = new HashMap<>();
        URL url = new URL(urlStr);
        String query = url.getQuery();

        if (query != null) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length > 1) {
                    query_pairs.put(keyValue[0], URLDecoder.decode(keyValue[1], "UTF-8"));
                } else {
                    query_pairs.put(keyValue[0], "");
                }
            }
        }
        return query_pairs;
    }
}
